﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EntitiesModel;
using IMCModel;

namespace ITMan
{
    public partial class FormPlat : Form
    {
        public FormPlat()
        {
            InitializeComponent();
        }

        //public IList<object> TblUsers ;
        public BindingSource bindingSource = new BindingSource();
        
        private void PlatForm_Load(object sender, EventArgs e)
        {
            dataGridViewUser.ReadOnly = true;
            tbUserId.ReadOnly = true;
            tbName.ReadOnly = true;
            tbLogid.ReadOnly = true;
            btSave.Enabled = false;
            //btEnableIMC.Enabled = false;

            dataGridViewUser.DataSource = null;
            var TblUsers = from u in new PlatEntities().Tbl_users
                           //where u.User_name == tbQuery.Text
                           orderby u.User_id descending
                           select new { u.User_id, u.User_name, u.Certification, u.User_create_time };
            if (!TblUsers.Any())
                MessageBox.Show("没有用户数据!");
            else
            {
                bindingSource.DataSource = TblUsers;
                dataGridViewUser.DataSource = bindingSource;
                dataGridViewUser.Columns["User_id"].HeaderText = "平台用户ID";
                dataGridViewUser.Columns["User_name"].HeaderText = "姓名";
                dataGridViewUser.Columns["Certification"].HeaderText = "证件号码";
                dataGridViewUser.Columns["User_create_time"].HeaderText = "创建日期";
            }
        }


        private void btQuery_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbQuery.Text))
            {
                dataGridViewUser.ClearSelection();
                PlatForm_Load(sender,e);
            }
            else
            {
                dataGridViewUser.DataSource = null;
                var TblUsers = from u in new PlatEntities().Tbl_users
                               where u.User_name.Contains(tbQuery.Text) || u.Certification.Contains(tbQuery.Text)
                               orderby u.User_id descending
                               select new { u.User_id, u.User_name, u.Certification, u.User_create_time };
                if (!TblUsers.Any())
                    MessageBox.Show("没有用户名为'"+tbQuery.Text+"'的用户!");
                else
                {
                    bindingSource.DataSource = TblUsers;
                    dataGridViewUser.DataSource = bindingSource;
                    dataGridViewUser.Invalidate();
                    dataGridViewUser.Columns["User_id"].HeaderText = "平台用户ID";
                    dataGridViewUser.Columns["User_name"].HeaderText = "姓名";
                    dataGridViewUser.Columns["Certification"].HeaderText = "证件号码";
                    dataGridViewUser.Columns["User_create_time"].HeaderText = "创建日期";
                    dataGridViewUser.Refresh();
                }

            }

        }

        private void dataGridViewUser_SelectionChanged(object sender, EventArgs e)
        {
            dataGridViewUser.ClearSelection();
            if (dataGridViewUser.CurrentCellAddress.Y > -1)
            {
                tbUserId.DataBindings.Clear();
                tbUserId.DataBindings.Add("Text", bindingSource, "User_id");
                tbName.DataBindings.Clear();
                tbName.DataBindings.Add("Text", bindingSource, "User_name");
                tbLogid.DataBindings.Clear();
                tbLogid.DataBindings.Add("Text", bindingSource, "Certification");
                dataGridViewUser.Refresh();
            }
        }

        private void radioOn_CheckedChanged(object sender, EventArgs e)
        {
            dataGridViewUser.ClearSelection();
            //dataGridViewUser.CurrentCell = null;
            //dataGridViewUser.Rows[0].Selected = false;
            if (radioOn.Checked)
            {
                var TblUsers = from u in new PlatEntities().Tbl_users
                               where u.Status==0
                               orderby u.User_id descending
                               select new { u.User_id, u.User_name, u.Certification, u.User_create_time };


                bindingSource.DataSource = TblUsers;
                dataGridViewUser.DataSource = bindingSource;
                dataGridViewUser.Columns["User_id"].HeaderText = "平台用户ID";
                dataGridViewUser.Columns["User_name"].HeaderText = "姓名";
                dataGridViewUser.Columns["Certification"].HeaderText = "证件号码";
                dataGridViewUser.Columns["User_create_time"].HeaderText = "创建日期";
                dataGridViewUser.Refresh();
            }
        }

        private void radioOff_CheckedChanged(object sender, EventArgs e)
        {
            dataGridViewUser.ClearSelection();
            //dataGridViewUser.CurrentCell = null;
            //dataGridViewUser.Rows[0].Selected = false;
            if (radioOff.Checked)
            {
                var TblUsers = from u in new PlatEntities().Tbl_users
                               where u.Status == 1
                               orderby u.User_id descending
                               select new { u.User_id, u.User_name, u.Certification, u.User_create_time };

                bindingSource.DataSource = TblUsers;
                dataGridViewUser.DataSource = bindingSource;
                dataGridViewUser.Columns["User_id"].HeaderText = "平台用户ID";
                dataGridViewUser.Columns["User_name"].HeaderText = "姓名";
                dataGridViewUser.Columns["Certification"].HeaderText = "证件号码";
                dataGridViewUser.Columns["User_create_time"].HeaderText = "创建日期";
                dataGridViewUser.Refresh();
            }
        }

        private void radioAll_CheckedChanged(object sender, EventArgs e)
        {
            PlatForm_Load(sender,e);
        }

        private void btCreate_Click(object sender, EventArgs e)
        {
            tbName.ReadOnly = false;
            tbLogid.ReadOnly = false;
            btSave.Enabled = true;
            btCreate.Enabled = false;

            tbLogid.Text = null;
            tbName.Text = null;
            tbUserId.Text = null;

        }

        private void btSave_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbName.Text) && !string.IsNullOrEmpty(tbLogid.Text))
            {
                using (var dbcon = new PlatEntities())
                {
                    Tbl_user user = new Tbl_user();
                    user.User_name = tbName.Text;
                    user.User_group = 1;
                    user.Certification = tbLogid.Text;
                    user.Status = 0;
                    user.User_create_time = DateTime.Now;
                    user.Selfservice = 1;
                    //如需开通自助平台
                    //user.Selfservice = 2;
                    //user.Ss_name = tbLogid.Text;
                   // user.Ss_password = "";
                    dbcon.Add(user);
                    dbcon.SaveChanges();
                }
                PlatForm_Load(sender,e);
                btEnableIMC.Enabled = true;
                btCreate.Enabled = true;
            }
            else
            {
                MessageBox.Show("登录名、姓名都不能为空！");
            }
        }

        private void btEnableIMC_Click(object sender, EventArgs e)
        {
            long userid;
            if (!string.IsNullOrEmpty(tbName.Text) && !string.IsNullOrEmpty(tbLogid.Text))
            {
                var TblUsers = from u in new PlatEntities().Tbl_users
                               where u.Certification==tbLogid.Text
                               select new { u.User_id, u.User_name, u.Certification, u.User_create_time };
                if (!TblUsers.Any())
                    MessageBox.Show("应先将'" + tbName.Text + "'保存为平台用户!");
                else
                {
                    userid=TblUsers.FirstOrDefault().User_id;
                    var eadUsers = from u in new EadEntitiesModel().TBL_ACM_USERs
                                   where u.USER_NAME == tbLogid.Text
                                   select u;
                    if (!eadUsers.Any())
                    {
                        
                        using (var eadUserDBConn = new EadEntitiesModel())
                        {
                            //写入IMC接入用户
                            TBL_ACM_USER acmUser= new TBL_ACM_USER();
                            acmUser.PLAT_USER_ID = userid;
                            acmUser.USER_NAME = tbLogid.Text;
                            acmUser.USER_PASSWORD = "i+qcYXeC8k4=";
                            acmUser.FULL_NAME = tbName.Text;
                            acmUser.USER_GROUP_ID = 1;
                            acmUser.STATUS = 1;
                            acmUser.USER_CREATE_TIME = DateTime.Now;
                            acmUser.INVALID_TIME = Convert.ToDateTime("2038-01-01 00:00:00.000");
                            acmUser.ONLINE_LIMIT = 1;
                            acmUser.IDLE_TIMEOUT = 0;
                            acmUser.IF_SELF_MODIFY_PASSWORD = 1;
                            acmUser.IF_PASSWORD_POLICY = 0;
                            acmUser.FEE_TYPE = 2;
                            acmUser.CARD_PREPAY = 0;
                            acmUser.IF_SELF_PAY = 1;
                            acmUser.USER_TYPE = 1;
                            acmUser.IF_MANAGE_GUEST = 0;

                            eadUserDBConn.Add(acmUser);
                            eadUserDBConn.SaveChanges();

                            TBL_ACM_USER acm = (from u in eadUserDBConn.TBL_ACM_USERs where u.USER_NAME==tbLogid.Text select u).FirstOrDefault();
                            
                            //开通服务
                            TBL_ACM_SERVICE services= new TBL_ACM_SERVICE();
                            services.USER_ID = acm.USER_ID;
                            services.SERVICE_TEMPLATE_ID = 2;
                            services.SERVICE_NAME = tbLogid.Text + "@portal";
                            services.SERVICE_CREATE_TIME = DateTime.Now;
                            //人工修改SERVICE_CREATE_TIME为?
                            services.STATUS = 1;
                            //services.CHECKSUM = null;
                            services.CYCLE_PROCESS_STATUS = 1;
                            services.CYCLE_FAIL_TIMES = 0;
                            services.FEE_MODEL_TYPE = 1;
                            services.FEE_TYPE = 1;
                            services.IF_CHANGE_SERVICE = 0;

                            eadUserDBConn.Add(services);
                            eadUserDBConn.SaveChanges();

                            //product
                            TBL_ACM_SERVICE sv =
                                (from s in eadUserDBConn.TBL_ACM_SERVICEs
                                 where s.USER_ID == Convert.ToInt64(acm.USER_ID)
                                 select s).FirstOrDefault();
                            
                            TBL_USER_PRODUCT product= new TBL_USER_PRODUCT();
                            product.USER_ID = acm.USER_ID;
                            product.SERVICE_ID = sv.SERVICE_ID;
                            product.PRODUCT_ID = -1;
                            product.CREATED_T = DateTime.Now;
                            product.VALID_START_T = DateTime.Now;
                            product.CYCLE_TYPE = 0;
                            product.CYCLE_FINISHED = 0;
                            product.IF_FIRST_CYCLE = 1;
                            product.IF_BILL = 1;
                            product.FEE_CONTINUOUS = 0;
                            eadUserDBConn.Add(product);
                            eadUserDBConn.SaveChanges();
                        } 
                        

                        MessageBox.Show("用户'" + tbName.Text + "'开通IMC服务成功!");
                    }
                    else
                    {
                        MessageBox.Show("用户'" + tbName.Text + "'已开通过IMC!");
                    }
                }
            }
            else
            {
                MessageBox.Show("登录名、姓名都不能为空！");
            }
        }

        private void btDisable_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbName.Text) && !string.IsNullOrEmpty(tbUserId.Text))
            {
                string message = "您确定要停用'"+tbName.Text+"'的IMC服务吗？";
                string caption = "提示!";
                MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                DialogResult result;

                result = MessageBox.Show(this, message, caption, buttons);

                if (result == DialogResult.Yes)
                {
                    using (var dbcon = new EadEntitiesModel())
                    {
                        IQueryable<TBL_ACM_USER> users = (from u in dbcon.TBL_ACM_USERs
                                         where u.PLAT_USER_ID == Convert.ToInt64(tbUserId.Text)
                                         select u);
                        if (users.Any())
                        {
                            TBL_ACM_USER user = users.FirstOrDefault();

                            TBL_USER_PRODUCT product = (from p in dbcon.TBL_USER_PRODUCTs
                                                        where p.USER_ID == user.USER_ID
                                                        select p).FirstOrDefault();
                            TBL_ACM_SERVICE service = (from s in dbcon.TBL_ACM_SERVICEs
                                                       where s.USER_ID == user.USER_ID
                                                       select s).FirstOrDefault();
                            TBL_USER_IP_MAC_INFO mac = (from m in dbcon.TBL_USER_IP_MAC_INFOs
                                                                     where m.USER_ID == user.USER_ID
                                                                     select m).FirstOrDefault();
                            if (product!=null)
                            {
                                dbcon.Delete(product);
                            }
                            if (service!=null)
                            {
                                dbcon.Delete(service);
                            }
                            if (mac!=null)
                            {
                                dbcon.Delete(mac);
                            }
                            dbcon.Delete(user);
                            dbcon.SaveChanges();

                            PlatForm_Load(sender, e);
                            btEnableIMC.Enabled = true;
                            MessageBox.Show("用户停用成功，已删除其服务及绑定的MAC地址");
                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show("IMC中已不存在此用户！");
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请先选择用户！");
            }


            //1.删除product
            //2.删除服务
            //3.删除绑定MAC
            //4.删除用户
            /*              
             DELETE FROM ead.TBL_USER_PRODUCTS WHERE USER_ID IN(select USER_ID FROM ead.TBL_ACM_USER WHERE USER_NAME='imc')             
             DELETE FROM ead.TBL_ACM_SERVICE WHERE USER_ID IN(select USER_ID FROM ead.TBL_ACM_USER WHERE USER_NAME='imc')
             DELETE FROM EAD.TBL_USER_IP_MAC_INFO WHERE USER_ID IN(select USER_ID FROM ead.TBL_ACM_USER WHERE USER_NAME='imc')             
             DELETE FROM ead.TBL_ACM_USER WHERE USER_NAME IN('imc')
            */
        }

        private void dataGridViewUser_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            ;
        }

        private void tbQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btQuery_Click(sender,e);
            }
        }   
    }
}
